import * as cp from 'child_process';
import * as vscode from 'vscode';

import * as path from 'path';
import * as fs from 'fs';


export function getParentCompileDir(filePath: string): string | null {
    // 检查当前目录是否有 Android.mk
    if (fs.existsSync(path.join(filePath, 'Android.mk')) || fs.existsSync(path.join(filePath, 'Android.bp'))) {
        return filePath;
    }

    // 分割路径，去除最后一个部分，得到父级目录
    const parentPath = path.dirname(filePath);

    // 如果已经到了根目录，则返回 null
    if (parentPath === filePath) {
        return null;
    }

    // 递归查找父级目录
    return getParentCompileDir(parentPath);
}

export function interceptErr(error: cp.ExecException | null, cb?: (error: cp.ExecException | null) => void) {
    if (cb && error) {
        return cb(error);
    }
    if (error) {
        console.error(`stderr: ${error.message}`);
        throw error;
    }
}

export function getEditor() {
    const editor = vscode.window.activeTextEditor;

    if (!editor) {
        vscode.window.showErrorMessage('No active editor.');
        throw new Error('No active editor.');
    }
    return editor;
}